package pers.cz.encrypt;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

/**
 * MD5加密工具
 * @program: PostGirl-panent
 * @description: Md5Util
 * @author: Cheng Zhi
 * @create: 2022-03-10 18:02
 **/
public class Md5Util {

    //加密方法
    public static String Md5(String content)  {
        //定义用于加密的字符 十六进制
        char [] md5Str={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
        try{
            //将传入的字符设置为utf-8字符编码
            byte[] byteInput = content.getBytes(StandardCharsets.UTF_8);

            //信息摘要
            MessageDigest mdins = MessageDigest.getInstance("MD5");

            //数据处理
            mdins.update(byteInput);

            //处理摘要后的信息HASH散列
            byte[] digest = mdins.digest();

            //将密文转换为十六进制字符串格式
            int j = digest.length;
            System.out.println("信息摘要后的十六进制字符串长度为:"+digest.length+"信息摘要后的十六进制字符串toString后:"+digest.toString());
            char [] str = new char[j*2];
            int k=0;
            for (int i=0;i<j;i++){
                byte bytes = digest[i];
                str[k++]=md5Str[bytes >>> 4 & 0xf];
                str[k++]=md5Str[bytes & 0xf];
            }
            //返回加密后的字符串
            return new String(str);
        }catch (Exception e){
            return "";
        }

    }
}
